package exporter;

import inporter.TokenInporter;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import main.tokens;

public class TextFileEditor {
	private Hashtable<String, ArrayList<tokens>> htAlphaTokens;
	
	//get tokens from files
	TokenInporter clsTInporter = new TokenInporter();
	Hashtable<String, String> htFileTokens;

	public TextFileEditor(Hashtable<String, ArrayList<tokens>> pAlphaTokens) 
	{
		htAlphaTokens = pAlphaTokens;
		
		//get tokens from files				
		clsTInporter.arlGetFileLines("input\\source.txt");
		htFileTokens = clsTInporter.getFileToken();
	}

	public void EditText(String pCntFileLoc, String pNewFileLoc) 
	{
		try 
		{
			FileReader reader = new FileReader(pCntFileLoc);

			PrintWriter out = new PrintWriter(new BufferedWriter(
					new FileWriter(pNewFileLoc)));

			BufferedReader br = new BufferedReader(reader);
			String strCntLine = null;
			String strAdd = "";

			String strCntToken = "";
			
			String s = "[a-z]+";
			Pattern pattern=Pattern.compile(s);
			
			while ((strCntLine = br.readLine()) != null) 
			{
				// For current line
				String strTokenTemp[] = strCntLine.split(" ");
				
				for (int i = 0; i < strTokenTemp.length; i++) 
				{
					 Matcher ma=pattern.matcher(strTokenTemp[i].toLowerCase());
				     if (ma.find())
				     {
				    	 strCntToken = ma.group();
				     }
				     
					// Check it is a non-dictionary token or not first 
					if (htAlphaTokens.get(strCntToken) != null) 
					{
						String strCntResult = htAlphaTokens.get(strCntToken).get(0).getResult().trim();
						strAdd = strRefineResult(strCntResult).replace(",  ", " ");
					}
				}
				out.println(strCntLine + strAdd);
				strAdd = "";
			}
			br.close();
			reader.close();
			out.close();
		} catch (Exception e) {
			System.err.println("Error: " + e.getMessage());
		}
	}
	
	private String strRefineResult(String pCntResults)
	{
		String strRtn = "";
		
		String[] strsCntResults = pCntResults.split(", ");
		for (int i = 0; i < strsCntResults.length; i ++)
		{
			String[] strsCntResult = strsCntResults[i].split(" ");
			for (int j = 0; j < strsCntResult.length; j ++)
			{
				if (htFileTokens.get(strsCntResult[j]) != null)
				{
					strRtn = strRtn + strsCntResult[j];
				}
				strRtn = strRtn + ", ";
			}			
		}
		
		return strRtn;
	}
}
